<template>
    <div class="base-page">
        <!-- 列表 -->
        <div class="right" style="margin: 0;" v-if="viewList === true">
            <div class="e-table">
                <div class="top">
                    <div class="left">
                        <div class="left-btn">
                            <el-button type="primary" size="mini"
                                @click="goAdd"
                                class="btn-greenYellow"
                            >新增</el-button>
                        </div>
                    </div>
                    <div class="search_box">
                        <el-input class="ipt" type="text"
                            placeholder="分包商名称/所属机构"
                            v-model="searchKey"
                            @select="onSearch"
                            @change="onSearch"
                        ><img src="@/assets/search.png" slot="suffix" @click="onSearch" /></el-input>
                        <div class="adverse">
                            <el-button type="primary" size="small">高级搜索</el-button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="e-table">
                <el-table
                    :style="{width: rightTableWidth}"
                    :height="rightTableHeight"
                    :data="tableData"
                    border
                    @selection-change="handleSelectionChange"
                    class="table"
                >
                    <el-table-column label="编号" type="index" width="55" fixed> </el-table-column>
                    <el-table-column prop="subcontractorName" label="分包商名称" min-width="150"
                        class-name="blue-column"
                    >
                        <template slot-scope="{ row }">
                            <span @click="onEdit(row)">{{ row.subcontractorName || '无'}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column  min-width="150" prop="warehouseName" label="仓库名称"> </el-table-column>
                    <el-table-column  min-width="150" prop="orgName" label="所属机构"> </el-table-column>
                </el-table>
            </div>
             <ComPagination
        :total="paginationInfo.total"
        :pageSize.sync="paginationInfo.pageSize"
        :currentPage.sync="paginationInfo.currentPage"
        @currentChange="currentChange"
        @sizeChange="sizeChange"
      />
        </div>
        <!-- 新增编辑界面 -->
        <div class="right" v-else>
            <div class="e-form">
                <div class="tabs scroll_bar"
                    id="tabs"
                    :style="{width: rightTabsWidth, height: rightTabsHeight, overflow: 'auto'}"
                >
                    <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
                        <el-tab-pane label="基本信息" name="baseInfo" :disabled="clickTabFlag"></el-tab-pane>
                        <el-tab-pane label="仓库信息" name="Warehouse" v-if="!viewList" :disabled="clickTabFlag" ></el-tab-pane>
                        <el-tab-pane label="附件信息" name="enclosure" v-if="!viewList" :disabled="clickTabFlag" ></el-tab-pane>
                        <!-- 基本信息 -->
                        <div id="baseInfoCon" class="con">
                            <el-form ref="formData" :model="formData"  :rules="rules" label-width="150px">
                                 <el-row style="margin-top:20px">
                                    <el-col :span="12" v-if="viewList !== 'add'">
                                        <el-form-item label="编号：">
                                            {{ formData.billNo }}
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="所属机构：">
                                            {{ formData.orgName }}
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                 <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="类型：" prop="warehouseType"
                                        >
                                            <el-radio disabled v-model="formData.warehouseType" :label="0" >项目部</el-radio>
                                            <el-radio disabled v-model="formData.warehouseType" :label="1" >分包商</el-radio>
                                        </el-form-item>
                                    </el-col>
                                      <el-col :span="12">
                                        <el-form-item label="操作人员：">
                                            {{ formData.operatorName }}
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="分包单位名称：" prop="subcontractorName">
                                            <el-input v-model="formData.subcontractorName" placeholder="请选择分包单位
                                            " readonly>
                                                <i slot="suffix" class="el-icon-document-copy" @click="onFbUnit"
                                                ></i>
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </div>
                        <!-- 仓库信息 -->
                        <div id="WarehouseCon" class="con"  v-show="!viewList">
                            <div class="tabs-title" id="Warehouse">仓库信息</div>
                            <div class="e-table">
                                <div style="margin: 0 0 10px;" v-if="viewList !== 'add'"  >
                                    <el-button type="primary" size="mini"
                                        @click="onAddSub"
                                        class="btn-greenYellow"
                                    >新增</el-button>
                                </div>
                                <el-table
                                    :data="tableData3"
                                    border
                                    :cell-class-name="cellClsNm"
                                    @selection-change="handleSelectionChangeSub"
                                >
                                 <el-table-column label="序号" type="index" width="75"> </el-table-column>
                                    <el-table-column prop="subcontractorName" label="操作"
                                        class-name="blue-column" width="75"
                                    >
                                        <template slot-scope="{ row }">
                                            <i class="el-icon-delete"
                                                style="font-size: 24px; color: #e9513e;"
                                                @click="onDelSub(row)"
                                                title="删除"
                                            ></i>
                                        </template>
                                    </el-table-column>
                                        <el-table-column label="仓库名称">
                                            <template slot-scope="{ row }">
                                            <el-input @input="input(row)" placeholder="请输入仓库名称" v-model="row.name"></el-input>
                                        </template>
                                        </el-table-column>
                                </el-table>
                            </div>
                        </div>
                        <!-- 附件信息 -->
                        <div id="WarehouseCon" class="con" v-show="!viewList" >
                            <div class="tabs-title" id="enclosure">附件信息</div>
                            <div  class="e-table">
                                <AttachComp
                                    :bucketName="bucketName"
                                    :relationId="relationId"
                                ></AttachComp>
                            </div>
                        </div>
                        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
                    </el-tabs>
                </div>
            </div>
            <div class="footer">
                <div class="right-btn">
                    <el-button type="primary" size="mini"
                        @click="onSave"
                    >保存</el-button>
                    <el-button type="primary" size="mini"
                        class="btn-delete"
                        @click="onDel"
                        v-if="viewList!='add'"
                    >删除</el-button>
                    <el-button size="mini"
                        @click="onCancel"
                    >取消</el-button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import ComPagination from '@/components/pagination/pagination'
import AttachComp from '@/components/common/attachIndex'
// import { deleterRecordIdAttach } from '@/api/base/system'
// eslint-disable-next-line no-unused-vars
import { warehouseAdd, warehouseListAdd, warehouseLs, warehouseGetById, warehouseGetLs, warehouseModify, warehouseModifyList, warehouseDel } from '@/api/base/warehouse'
// eslint-disable-next-line no-unused-vars
import { debounce, showLoading, hideLoading, selectDataClient, openAppClient, getUuid } from '@/utils/common'
import { mapMutations, mapState } from 'vuex'
import { ip } from '@/utils/request'
export default {
    components: {
        ComPagination, AttachComp
    },
    computed: {
        ...mapState(['userInfo']),
        orgCode () {
            return this.userInfo.orgInfo.shortCode
        },
        relationId () {
            return this.formData.billId
        },
        // 列表宽度
        rightTableWidth () {
            return (this.screenWidth - 20) + 'px'
        },
        rightTableHeight () {
            if (this.paginationInfo.total > 0) {
                return this.screenHeight - 170
            } else {
                return this.screenHeight - 118
            }
        },
        // tabs内表格宽度
        rightTabsWidth () {
            return (this.screenWidth - 22) + 'px'
        },
        rightTabsHeight () {
            return (this.screenHeight - 74) + 'px'
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 115 - this.lastConHeight
        },
        // 剔除changeType为-1的值【前端删除功能】
        tableData3 () {
            return this.tableData2.filter(item=>{
                return item.changeType != -1
            })
        }
    },
    data () {
        return {
            isChoice: true, //是否禁用选择分包单位默认禁用
            viewList: true, // 显示列表还是编辑界面: true 显示列表 false 显示编辑界面
            bucketName: 'base',
            searchKey: '', //高级搜索
            treeData: [],
            selectedData: [],
            selectedDataSub: [],
            curSelectOrg: {
                orgId: '',
                orgName: ''
            },
            paginationInfo: {
                total: 0,
                pageSize: 20,
                currentPage: 1,
            },
            attachTableData: [],
            formData: {
                warehouseType: 1
            },
            currencyOptions: [],
            tabsName: 'baseInfo',
            tableData: [],
            tableData2: [],
            uploadUrl: ip + '/oss/uploader',
            accept: '.jpg,jpeg,.png,.pdf',
            currentRow: null,
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            idsTop: [],
            radio: '', //类型
            rules: {
                // 统一社会信用代码
                subcontractorName: [
                    { required: true, message: '请选择仓库名称', trigger: 'change' },
                ],
                //类型
                warehouseType: [
                    { required: true, message: '请选择类型', trigger: 'change' },
                ]
            },
        }

    },
    created () {
        this.getLs()//获取列表
    },
    mounted () {
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()
        // 获取屏幕宽高
        this.getScreenInfo()
        // 注册滚动事件
        this.registScroll()
        window.addEventListener('resize', debounce(this.getScreenInfo))
    },
    methods: {
        ...mapMutations(['setSelectedInfo']),
        // 取消禁用选择分包单位
        getWarehouseValue () {
            this.isChoice = false
        },
        // 获取列表
        async getLs () {
            showLoading()
            try {
                const resData = await warehouseLs({
                    keyword: this.searchKey, //物资名称
                    limit: this.paginationInfo.pageSize, //每页显示条数
                    page: this.paginationInfo.currentPage, //当前页
                    // orgId: this.userInfo.orgInfo.orgId, //当前机构
                    orgId: '', //当前机构
                })
                this.tableData = resData.list
                this.paginationInfo.total = resData.totalCount
                hideLoading()
            } catch {
                hideLoading()
            }
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },
        // 分包商人员选择方法
        onSearch (e) {
            let searchKey = e
            if (typeof e === 'object') {
                searchKey = this.searchKey
            }
            console.log(searchKey)
        },
        // 新增仓库明细方法
        goAdd () {
            this.viewList = 'add'
            this.formData = {
                billId: '', //仓库id
                billNo: '', //编号
                subcontractorId: this.curSelectOrg.orgId, //分包商id
                subcontractorName: this.curSelectOrg.orgName, //分包商名称
                warehouseType: 1, //库房类型
                operatorId: this.userInfo.userId, //操作人id
                operatorName: this.userInfo.userName, //操作人名称
                orgId: this.userInfo.orgInfo.orgId, //所属机构id
                orgName: this.userInfo.orgInfo.orgName//所属机构名称
            }
            this.tableData2 = []
            this.$nextTick(() => {
                $('#tabs').scrollTo(0, 0)
            })
        },
        // 分包商点击编辑的方法
        async onEdit ({ billId }) {
            showLoading()
            try {
                // 获取仓库基本信息
                const resData = await warehouseGetById({
                    id: billId
                })
                // 获取仓库详细信息
                const resData2 = await warehouseGetLs({
                    id: billId
                })
                // 将请求回来的仓库基本信息赋值
                this.formData = resData
                this.tableData2 = ('data' in resData2 ? resData2.data : resData2) || []
                this.tableData2.forEach(item => {
                    item.uuid = item.dtlId
                })
                this.viewList = false
                this.$nextTick(() => {
                    $('#tabs').scrollTo(0, 0)
                })
                hideLoading()
            } catch (error) {
                hideLoading()
            }
        },
        // 保存方法
        async onSave () {
            showLoading()
            this.$refs.formData.validate(  async valid =>  {
                if (valid) {
                    try {
                        // 如果没有仓库id，则为新增，否则为编辑
                        if (!this.formData.billId) {
                            await warehouseAdd(this.formData)
                        } else {
                            // 编辑保存
                            await warehouseModify(this.formData)
                            await warehouseModifyList(this.tableData2)
                        }
                        this.getLs()
                        this.viewList = true
                    } catch (err) {
                        hideLoading()
                    }
                } else {
                    hideLoading()
                    return false
                }
            })
        },
        // 删除整条基本信息
        onDel () {
            this.clientPop('info', '确定要删除吗？数据删除后不可恢复，请谨慎操作！', async () => {
                // 获取币种设置列表
                showLoading()
                try {
                    await warehouseDel({
                        id: this.formData.billId
                    })
                    this.clientPop('suc', '删除成功', () => {
                        this.viewList = true
                        this.getLs()
                    })
                } catch (e) {
                    hideLoading()
                }
            })
        },
        onCancel () {
            this.viewList = true
        },
        // 新增仓库信息
        onAddSub () {
            this.tableData2.push({
                uuid: getUuid(),
                changeType: 1, //变更类型，【-1：删除，0：未变更,1：新增,2:变更】
                name: '',
                billId: this.formData.billId, //仓库管理id
                dtlId: '', //仓库明细id
            })
        },
        // //监听明细数据input事件【修改过后将数据状态改为2】
        input (row) {
            // 没有dtlId则为新增的数据，新增的数据不更改changeType
            if(row.dtlId) {
                row.changeType = 2
            }
        },
        // 删除仓库明细数据
        onDelSub ({ uuid, dtlId }) {
            // 如果是后台已有数据，则标记状态
            if (dtlId) {
                this.clientPop('info', '确定要删除吗？数据删除后不可恢复，请谨慎操作！', () => {
                    this.tableData2.map(item=>{
                        if(uuid === item.uuid) {
                            item.changeType = -1
                        }
                    })
                }, null, () => {
                    console.log('取消')
                })
            } else {
                // 否则直接删除
                const findIndex = this.tableData2.findIndex(item => uuid === item.uuid)
                this.tableData2.splice(findIndex, 1)
            }
        },
        // 选中分包商
        handleSelectionChange (val) {
            this.selectedData = val
        },
        // 选中人员信息
        handleSelectionChangeSub (val) {
            this.selectedDataSub = val
        },
        // 选择分包单位
        onFbUnit () {
            if(this.formData.warehouseType) {
                // 项目部包含 1 供应商 2 往来单位 3 事实外包方
                const currentList = this.formData.warehouseType == '1' ? [0, 1, 2, 3] : [1, 2, 3]
                selectDataClient({
                    SelectServiceToken: 'GeneralSelectOuter', // 客户端对应方法名
                    IsSingleMode: true, // 是否单选 true 单选 false 多选
                    SelectedIDs: [], // 已选中id
                    Title: '选择分包单位', // 标题
                    InitParamsStr: JSON.stringify({
                        'keyword': '',
                        'limit': 10,
                        'orgId': '',
                        'page': 1,
                        'states': [],
                        'type': currentList // 0 分包商   1 供应商   2 往来单位   3 事实外包方
                    })
                }).then(val => {
                    this.curSelectOrg = val[0]
                    this.formData.subcontractorId = val[0].id
                    this.formData.subcontractorName = val[0].outerName
                })
            }
        },
        onChangeTab (e) {
            const cur = this.idsTop.find(item => item.name === e.name)
            $('#tabs').scrollTo(cur.top, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('enclosureCon')) {
                    const lastConHeight = document.getElementById('enclosureCon').offsetHeight
                    this.lastConHeight = lastConHeight - 18
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        getScreenInfo () {
            let screenWidth = document.documentElement.clientWidth || document.body.clientWidth
            let screenHeight = document.documentElement.clientHeight || document.body.clientHeight
            this.screenWidth = screenWidth
            this.screenHeight = screenHeight
        },
        // 注册右侧tabs区域内滚动时定位
        registScroll () {
            let si = setInterval(() => {
                if (document.getElementById('tabs')) {
                    // 保存所有tabName
                    const arr = ['baseInfo', 'Warehouse', 'enclosure']
                    const me = this
                    let $idsTop = []
                    if (!$idsTop[$idsTop.length - 1]) {
                        $idsTop = arr.map(item => {
                            const $item = document.getElementById(item)
                            let itemTop = 0
                            if ($item) {
                                itemTop = $item.offsetTop
                            }
                            return {
                                name: item,
                                top: itemTop
                            }
                        })
                    }
                    this.idsTop = $idsTop

                    $('#tabs').on('scroll', function () {
                        // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
                        if (me.clickTabFlag) {
                            return
                        }

                        const scrollTop = $(this).get(0).scrollTop
                        // 倒序查找
                        let curLocal = 0
                        for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                            let item = $idsTop[i].top
                            if (scrollTop + 3 >= item) {
                                curLocal = i
                                break
                            }
                        }
                        // 设置对应tabName
                        me.tabsName = arr[curLocal]
                    })

                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        //翻页
        currentChange () {
            this.getLs()
        },
        //改变条数
        sizeChange () {
            this.getLs()
        }
    }
}
</script>

<style lang="scss" scoped>
.base-page {
    .right{
        margin: 0;
        .tabs {
            ::v-deep .el-tabs__header {
                left: 12px;
            }
        }
    }
}
::v-deep.el-input__suffix{
    display: flex;
    align-items: center;
}
::v-deep .el-table__header{
    width: 100% !important;
}
.btn{
    width: 80px;
     margin-right: 10px;
}
</style>
